package com.lx.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lx.base.datacopy.DataCopy;
import com.lx.base.datacopy.Dataproperty;
import com.lx.base.datacopy.impl.ListCopy;
import com.lx.base.datacopy.impl.StringCopy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
@Slf4j
public class BaseBeanUtills {
    private static Map<String,DataCopy> DEFAULT_DataCopy=new HashMap<String,DataCopy>();
    static{
        DEFAULT_DataCopy.put(List.class.getTypeName(),new ListCopy());
        DEFAULT_DataCopy.put(String.class.getTypeName(),new StringCopy());
    }
    public static <T>T  copyProperties(Object source,Class<T> targetType){
        String sourceJsonString= JSON.toJSONString(source);
        JSONObject result=JSON.parseObject(sourceJsonString);
        //处理需要特殊转换的数据
        Map<String,Class<?>> sourceFieldType=ReflectUtil.getFieldType(source.getClass());
        Map<String,Class<?>> targetFieldType=ReflectUtil.getFieldType(targetType);
        JSONObject   sourceAnno=ReflectUtil.getFieldAnno(source.getClass(),Dataproperty.class);
        DataCopy dataCopy=null;
        for(String key:sourceFieldType.keySet()){
            dataCopy=getDataproperty(sourceFieldType,targetFieldType,sourceAnno,key);
            if(dataCopy!=null){
                String before=result.getString(key);
                if(!StringUtils.isEmpty(before)){
                String after= dataCopy.converter(before,targetFieldType.get(key));
                result.put(key,after);
            }
        }
        }
        return result.toJavaObject(targetType);
    }

    private  static DataCopy getDataproperty(Map<String,Class<?>> sourceFieldType, Map<String,Class<?>> targetFieldType, JSONObject   sourceAnno, String key) {
       //1 注明了转换方式
        if(sourceAnno.containsKey(key)){
            Dataproperty dataproperty= (Dataproperty)sourceAnno.get(key);
            try {
                return    dataproperty.converter().newInstance();
            } catch (Exception e) {
                log.error("数据转换实例化DataCopy异常:{}",e);
                return null;
            }
        }
        String source=sourceFieldType.get(key).getName();
        if(!targetFieldType.containsKey(key)){
            return null;
        }
        String target=targetFieldType.get(key).getName();
        //2 类型一致的
        if(source.equals(target)){
            return null;
        }
        //3 使用默认的
       return DEFAULT_DataCopy.get(source);
    }

}
